package vip.mtdp.usercenter.service.rpc.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;
import vip.mtdp.common.CommonConstant;
import vip.mtdp.common.exception.AppRTException;
import vip.mtdp.customer.api.MerchantRpcService;
import vip.mtdp.customer.api.PartyEnum;
import vip.mtdp.customer.api.PersonRpcService;
import vip.mtdp.customer.api.dto.MerchantDTO;
import vip.mtdp.customer.api.dto.PersonDTO;
import vip.mtdp.usercenter.dal.dao.UserMapper;
import vip.mtdp.usercenter.dal.domain.User;
import vip.mtdp.usercenter.dto.UserDTO;
import vip.mtdp.usercenter.service.UserRpcService;
import vip.mtdp.util.EncryptUtil;

/**
 * 
 *
 * @Description 用户服务实现
 * @author wangguoqing
 * @date 2017年9月17日下午2:21:18
 *
 */
@Slf4j
@Service
public class UserRpcServiceImpl implements UserRpcService {
	

	@Autowired
	private UserMapper userMapper;

	@Reference(version = "1.0.0")
	private PersonRpcService personRpcService;

	@Reference(version = "1.0.0")
	private MerchantRpcService merchantRpcService;

	@Transactional(rollbackFor = AppRTException.class)
	@Override
	public UserDTO createUser(UserDTO userDTO) throws AppRTException {
		log.debug("create user = {}",userDTO);
		//user
		if(userDTO == null || userDTO.getPartyId() == null){
			throw new AppRTException("param_is_not_null","user is not null");
		}
		User user = new User();
		BeanUtils.copyProperties(userDTO, user);
		Date d = new Date();
		user.setRegTime(d);
		user.setState(CommonConstant.ENALBED);
		user.setCreatedAt(d);
		user.setUpdatedAt(d);
		int cnt = userMapper.save(user);
		if(cnt == 1){
			userDTO.setUserId(user.getOid());
			return userDTO;
		}
		return null;
	}

	/**
	 * 更新用户信息
	 *
	 * @param userDTO
	 * @return
	 * @throws AppRTException
	 */
	@Override
	public UserDTO updateUser(UserDTO userDTO) throws AppRTException {
		log.info("update user userDTO = {}",userDTO);
		if(userDTO == null){
			throw new AppRTException("param_is_not_null","user is not null");
		}
		User user = new User();
		BeanUtils.copyProperties(userDTO,user);
		user.setUpdatedAt(new Date());
		userMapper.update(user);
		return userDTO;
	}


	@Override
	public boolean modifyUserPwd(UserDTO userDTO) throws AppRTException{
		User u = new User();
		u.setOid(userDTO.getUserId());
		String pwd = userDTO.getLoginPwd();
		//SHA 加密密码
		pwd = EncryptUtil.sha(pwd);
		u.setLoginPwd(pwd);
		u.setUpdatedAt(new Date());
		int cnt = userMapper.update(u);
		return cnt == 1 ? true : false ;
	}

	@Override
	public UserDTO login(String userName, String pwd) throws AppRTException {
		log.debug("login userName={}",userName);
		String mPwd = EncryptUtil.sha(pwd);
		User user = userMapper.login(userName, mPwd);
		if(user != null && CommonConstant.ENALBED.equals(user.getState())){
			//密码正确并且用户没有被冻结,检查客户是否被冻结
			boolean isFreeze = false;
			if(PartyEnum.PERSON.getValue().equals(user.getType())){
				PersonDTO personDTO = personRpcService.getPersonByPartyId(user.getPartyId());
				if(personDTO != null && CommonConstant.DISABLED.equals(personDTO.getPartyDTO().getStatus())){
					isFreeze = true;
				}
			}
			if(PartyEnum.MERCHANT.getValue().equals(user.getType())){
				MerchantDTO merchantDTO = merchantRpcService.getMerchantByPartyId(user.getPartyId());
				if(merchantDTO != null && CommonConstant.DISABLED.equals(merchantDTO.getPartyDTO().getStatus())){
					isFreeze = true;
				}
			}
			if(CommonConstant.BOOLEAN_TRUE.equals(user.getIsLock())){
				log.warn("userName = {},帐号被锁",userName);
				throw new AppRTException("account_is_lock");
			}
			if(isFreeze){
				log.warn("userName={},所属客户被冻结",userName);
				throw new AppRTException("account_freeze");
			}
			UserDTO userDTO = new UserDTO();
			BeanUtils.copyProperties(user, userDTO);
			userDTO.setUserId(user.getOid());
			return userDTO;
		}else{
			log.error("account not exist,userName = {}",userName);
			throw new AppRTException("account_not_exist");
		}
	}

	@Override
	public List<UserDTO> getUserByPartyId(Long partyId) throws AppRTException {
		List<User> mUsers = userMapper.getUserByPartyId(partyId);
		List<UserDTO> users = new ArrayList<UserDTO>();
		for(User user : mUsers){
			UserDTO userDTO = new UserDTO();
			BeanUtils.copyProperties(user, userDTO);
			userDTO.setUserId(user.getOid());
			if(PartyEnum.PERSON.getValue().equals(user.getType())){
				PersonDTO personDTO = personRpcService.getPersonByPartyId(partyId);
				userDTO.setPersonDTO(personDTO);
			}
			if(PartyEnum.MERCHANT.getValue().equals(user.getType())){
				MerchantDTO merchantDTO = merchantRpcService.getMerchantByPartyId(partyId);
				userDTO.setMerchantDTO(merchantDTO);
			}
			users.add(userDTO);
		}
		return users;
	}

	@Override
	public UserDTO getUserByUserId(Long userId) throws AppRTException {
		User u = userMapper.get(userId);
		UserDTO user = new UserDTO();
		BeanUtils.copyProperties(u, user);
		user.setUserId(u.getOid());
		return user;
	}

}
